package com.itheima.myTask;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.dao.SetmealDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 自定义定时任务类
 */
@Component
@Slf4j
public class Task {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 定时任务 每天晚上0点执行
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void executeTask(){
        log.info("定时任务开始执行：{}",new Date());
        SetOperations setOperations = redisTemplate.opsForSet();
        Set<String> membersSet1 = setOperations.members(RedisConstant.SETMEAL_PIC_RESOURCES);
        Set<String> membersSet2 = setOperations.members(RedisConstant.SETMEAL_PIC_DB_RESOURCES);

        //获取垃圾图片
        Set<String> difference = new HashSet<>(membersSet1);
        difference.removeAll(membersSet2);

        //删除垃圾图片
        for (String s : difference) {
            int lastIndex = s.lastIndexOf('/');
            String fileName = s.substring(lastIndex + 1);
            aliOssUtil.delete(fileName);
        }

        //清除垃圾图片图片之后删除redis ,set集合
        redisTemplate.delete(RedisConstant.SETMEAL_PIC_RESOURCES);
        redisTemplate.delete(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
    }
}
